<template>
  <div class="biz-container">
    <table-layout :haveSider="false" :isSearch="true">
      <template #headCustom>
          <div class="importTip">温馨提示：①下载标准编码进行编码对照，②下载编辑模板进行商品录入，③导入文件。</div>
          <!-- <a-button type="primary" size="large" style="marginRight:20px">新增</a-button> -->
          <import-hospital-store @ok="handleModalSaveOk"  ></import-hospital-store>
          <export-excel 
            ref="export" 
            style="marginLeft:20px"
            btnType="link" btnText="下载标准编码" size="large"
            @getExcelData="onDownloadStore"></export-excel>
          <export-excel 
            ref="export" 
            style="marginLeft:20px"
            btnType="link" btnText="下载编辑模板" size="large"
            @getExcelData="onDownloadDemo"></export-excel>
          <!-- 下载商品库（弹框选择商品库），下载空模板 -->
          <!-- <impot-standard-store></impot-standard-store> -->
      </template>
      <template #searchBox>
        <search-layout
          :formInfos="q_formInfos"
          :formDatas="q_formDatas"
          message=""
          @onFind="onFind"
          @onChangeType="onChangeType"
        ></search-layout>
      </template>
      <template #batchOperat>
        <batch-operat-btn 
          :addData="true" @onAddData="onAddData"
          :delectData="true" @onDelectData="onDelectData"
          :optData="optText" @onOptData="onBatchAudit"
        >
        </batch-operat-btn>
      </template>
      <template #tableList="slotData">
        <a-list-table
          :columns="columns"
          :tableData="listdata"
          :pagination="pagination"
          :isSelecttion="true"
          :loading="loading"
          :scroll="{y:slotData.tableHeight}"
          @onTableChange="handleTableChange"
          @onselectChange="onselectChange"
          @onAction="onAction"
          :links="links"
          @onTouchlinkCell="onTouchlinkCell"
          @onTouchCell="onTouchCell"
        >
        </a-list-table>
      </template>
    </table-layout>
     <viewModal ref="viewModal" @ok="handleModalSaveOk" @close="handleModalCancel" />
     <areaModal ref="areaModal" @ok="handleModalSaveOk" @close="handleModalCancel" />
  </div>
</template>

<script>
import searchLayout from '@/views/app/biz/common/searchLayout'
import batchOperatBtn from '@/views/app/biz/common/batchOperatBtn'
import tableLayout from '@/views/app/biz/common/index'
import aListInfo from '@/views/app/biz/common/aListInfo'
import aListTable from '@/views/app/biz/common/aListTable'
import viewModal from './viewModal' 
import areaModal from './areaModal.vue' 
import importHospitalStore from './importHospitalStore.vue'
import exportExcel from '@/views/app/biz/common/exportExcel/index.vue' 
import moment from 'moment'
import {
  getByAreaUse,
  getByAreaUseCount,
  deleteInfo,
  downloadData
} from './purchasedgoods'
import {
  columns,q_formInfos,q_formDatas
} from './dataConfig'

// 字段列表

let links=['areaDm']

export default {
  components: {
    searchLayout,
    batchOperatBtn,
    tableLayout,
    aListInfo,
    aListTable,
    viewModal,
    importHospitalStore,
    exportExcel,
    areaModal
  },
  data() {
    return {
      columns: columns,
      listdata: [],
      links:links,
      loading: false,
      pagination: {
        //分页配置
        current: 1, //当前页码 current
        pageSize: 10, //每页显示条数 pageSize
        total: 1,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ['2', '10', '50', '100','1000'],
      },
      // 查询表单
      q_formInfos: q_formInfos,
      // 查询表单绑定数据
      q_formDatas: q_formDatas,
      pData: {}, // 条件查询参数
      isJump:false,
      optText: '',
      selectedRowKeys: [],
      selectedRows: [],
      notAudit: false,
      side:null
    }
  },
  computed: {},
  watch: {
    $route: {
        handler: function (val, oldVal) {
          console.log(this.$route.name); 
          console.log(this.$route.meta);  
          //判断是进入该页面还是离开
          if (this.$route.name=='goodsStore' ) {
            //读取该页面是否缓存，未缓存时：
            if (!this.$route.meta.keepAlive) {
              //读取页面跳转传参
              if(this.$route.params.keHuPid){
                this.q_formDatas.keHuPid=this.$route.params.keHuPid
              }
              this.getTotal()
              this.getList(this.q_formDatas)
            }else{
              console.log(this.$route.params.isBack);
              //已缓存时判断是否是返回
              if (!this.$route.params.isBack) {
                this.getTotal()
                this.getList(this.q_formDatas)
              }
              this.isJump=false
            }
          }
        },
        deep: true,
        immediate:true
    }
  },
  beforeRouteEnter(to,from,next){
    console.log('beforeRouteEnter',to,from);
    next(vm=>{
      console.log(vm.isJump);
    });
  },
  beforeRouteLeave(to,from,next){
    if (this.isJump) {
      from.meta.keepAlive=true
    }else{
      from.meta.keepAlive=false
    }
    next();
  },
  mounted(){
    console.log('mounted');
    // this.getTotal()
    // this.getList(this.q_formDatas)
    
  },
  methods: {
    formatParms(){
      let sbdata=JSON.parse(JSON.stringify(this.q_formDatas))
      for (let key in sbdata) {
        console.log(key,sbdata[key]);
        if (!sbdata[key]){
          sbdata[key]=null  
        }
        if (key=='productNameZh' || key=='manufacturerZh') {
          if (sbdata[key]==null) {
            sbdata[key]=`%%`
          }else{
            sbdata[key]=`%${sbdata[key]}%`
          }
          
        }
      }
      return sbdata
    },
    // 初始化页面时得到总数
    async getTotal() {
      let pages = ''
      pages = await getByAreaUseCount(this.formatParms())
      console.log(pages)
      if (pages && pages.code && pages.code === 'C1') {
        const pagination = { ...this.pagination }
        pagination.total = pages.data
        this.pagination = pagination
        this.pagination.showTotal =  (showTotal) => {return `共 ${showTotal} 条`}
      }
    },
    // 初始化查询时的数据列表
    async getList(params) {
      console.log('请求列表时传入的数据', this.formatParms())
      let actionBtn=['编辑']
      this.loading = true
      let listdata = []
      let res = ''
      res = await getByAreaUse(this.formatParms(), this.pagination)
      this.loading = false
      console.log(res)
      if (res && res.code && res.code === 'C1' && res.data) {
        const resdata = res.data
         for (let item of resdata) {
            listdata.push({
               key: item.pid,
               standardCode:item.code,
               action:actionBtn,
               ...item
               }
            )
         }
         this.listdata =listdata
      } else {
        this.listdata = []
      }
      console.log(this.listdata)
    },
    // 新增按钮 点击了新增
    onAddData() {
      // this.$refs.addModal.addModal()
      this.$router.push({
        name: 'addGoods',
        params: {
          isJump:false,
          pathName:this.$route.name,
          pid:null,
          type:'add'
        } 
      })

    },
    // 关闭模态详细框
    handleModalCancel() {
    },
    // 模态详细框提交按钮
    handleModalSaveOk() {
      this.getList(this.q_formDatas)
    },
    // 操作按钮
    onAction(text, record, index) {
      if (text == '编辑') {
        //修改
        // this.$refs.addModal.editModal(record.pid) 
        this.$router.push({
          name: 'addGoods',
          params: {
            isJump:false,
            pathName:this.$route.name,
            pid:record.pid,
            type:'edit'
          } 
        })
        // this.showConfirm(record)
      }else if (text == '查看'){ 
        this.$refs.viewModal.showModal(record.pid)
      }else if (text == '发票'){ 
        this.$refs.invoiceModal.showModal(record.pid,record)
      }
    },

    // 触发改变页码,筛选,排序时的回调
    handleTableChange(pagination, filters, sorter) {
      this.pagination.current = pagination.current
      this.pagination.pageSize = pagination.pageSize
      this.getList(this.q_formDatas)
    },
    //下载商品数据
    onDownloadStore(){
      this.$refs.areaModal.showModal(null,null)
    },
    //下载空模板
    onDownloadDemo(){
      //x下载模板，如需请求数据，则在此请求数据后执行以下
      this.downloadData()
      // let listName="基础商品信息"
      // let listHeader=['商品自编码','商品名称','一级分类（学科、品类）','二级分类（用途、品目）','三级分类（部位、功能、品种）','品牌']
      // let listField=['code','productNameZh','first','second','third','brand']
      // let exportList=[]
      // this.$refs.export.setData(listName,listHeader,listField,exportList)
    },
    async downloadData(){
      let pa = {areaUse:'template'}
      let res = await downloadData(pa)
      console.log(res)
      if (res) {
        let downFileName= moment(new Date).format("YYYYMMDDhhmmss")
        // let downFileName=record.areaCT+'_'+optTime
        if (typeof window.chrome !== 'undefined') {
          // Chrome version
          const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
          const urls = window.URL.createObjectURL(blob)
          const a = document.createElement('a') // 生成虚拟a标签
          a.href = urls
          a.download = downFileName + '.xlsx'
          a.click()
          // document.body.remove(a) // 下载完成移除元素
          window.URL.revokeObjectURL(urls) // 释放掉blob对象
        } else if (typeof window.navigator.msSaveBlob !== 'undefined') {
          // IE version
          const blob = new Blob([res], { type: 'application/force-download' })
          window.navigator.msSaveBlob(blob, downFileName)
        } else {
          // Firefox version
          const file = new File([res], downFileName, { type: 'application/force-download' })
          window.open(URL.createObjectURL(file))
        }
      }
    },
    // 搜索栏选择下拉select触发搜索val[0]表示选中的record中的pid,val[1]表示选中的record全部信息
    onChangeType(name, val) {
      console.log('formName',name)
      console.log('val',val)
      switch (name) {
        case 'pid': 
          if (!val[0]) {
            this.q_formDatas.pid=null
          }
          this.onFind ()
          break 
        case 'approvalNum':
          if (!val) {
            this.q_formDatas.approvalNum=null
          }
          this.onFind ()
          break
        case 'state':
          if (!val) {
            this.q_formDatas.state=null
          }
          this.onFind ()
          break
      }
    },
    // 查询按钮
    onFind (){
      this.pagination.current = 1
      this.getTotal()
      this.getList(this.q_formDatas)
    },
    onTouchCell( text, record, index,link){
      this.$refs.viewModal.showModal(record.pid)
    },
    onTouchlinkCell( text, record, index,link){
      console.log(record);
      if(link=='areaDm'){
        this.$refs.viewModal.showModal(record.pid)
      }
    },
    // 多选批量操作
    onselectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      for (const item of this.selectedRows) {
        if (item.zhuangTai != '待审核') {
          this.notAudit = true
          return
        } else {
          this.notAudit = false
        }
      }
    },
    onDelectData(){
      if(this.selectedRows.length){
        this.showDelConfirm(this.selectedRows)
      }else{
        this.$message.warning({ content:'未选择要删除的记录', duration: 3 })
      }
    },
    showDelConfirm(val,type) {
      let datas=[]
      if(type=='1'){
        datas[0]=val
      }else{
        datas=val
      }
      const that = this;
      this.$confirm({
        title: '是否确认删除？',
        content: '删除后不可恢复！',
        onOk() {
          let reqArr=[]
          let key='self'
          for (const item of datas) {
            reqArr.push(that.delOrder(item))
          }
          return Promise.all(reqArr).then(res => {
            console.log(res);
            for (const item of res) {
              console.log(item);
              if (item && item.code && item.code === 'C1' && item.data) {
                that.$message.success({ content:'记录删除成功', duration: 3 })
              } else {
                that.$message.error({ content:'记录删除失败，原因：'+item.message, duration: 3 })
              }
            }
            that.handleModalSaveOk()
          }).catch(err => {
            that.$message.error({ content:'操作出错:'+err, duration: 3 })
          })
        },
        onCancel() {},
      });
    },
    async delOrder(val){
      let res = await deleteInfo(val)
      return res
    },
    onBatchAudit() {
      if (this.selectedRows.length) {
        if (this.notAudit) {
          this.$message.warning({ content: '已选项中含有已审核的记录，请选择待审核的记录', duration: 3 })
        } else {
          this.$refs.auditModal.batchModal(this.selectedRows)
        }
      } else {
        this.$message.warning({ content: '未选择要审核的记录', duration: 3 })
      }
    }
  },
}
</script>

<style>
.importTip{
  line-height: 40px;
  font-size: 14px;
  color: #fab600;
}
</style>